package observer;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 作物生长监测器
 * 用于监测作物生长状态
 */
public class CropGrowthMonitor {
    private final String cropType;
    private final EnvironmentSensor heightSensor;
    private final EnvironmentSensor stageSensor;
    private final Random random;

    // 定义生长阶段
    private static final String[] GROWTH_STAGES = {
            "种子", "发芽", "幼苗", "生长期", "开花期", "结果期", "成熟期"
    };

    public CropGrowthMonitor(String cropType) {
        this.cropType = cropType;
        this.heightSensor = new EnvironmentSensor(cropType + "高度");
        this.stageSensor = new EnvironmentSensor(cropType + "生长阶段");
        this.random = new Random();

        // 初始化传感器值
        heightSensor.setValue(0.0);
        stageSensor.setValue(0.0); // 0表示种子阶段
    }

    /**
     * 更新作物生长状态
     */
    public void updateGrowthStatus(double height, int stageIndex) {
        heightSensor.setValue(height);
        stageSensor.setValue(stageIndex);
        printStatus(height, GROWTH_STAGES[stageIndex]);
    }

    /**
     * 自动监测作物生长
     */
    public void autoMonitor() {
        // 获取当前高度和阶段
        double currentHeight = heightSensor.getCurrentValue();
        int currentStageIndex = (int) stageSensor.getCurrentValue();

        // 更新高度
        double growthRate = 0.5 + random.nextDouble() * 2.5;
        double newHeight = currentHeight + growthRate;
        newHeight = Math.round(newHeight * 10) / 10.0; // 保留一位小数

        // 检查是否需要更新生长阶段
        int newStageIndex = getStageByHeight(newHeight);

        // 更新生长状态
        updateGrowthStatus(newHeight, newStageIndex);
    }

    /**
     * 根据高度确定生长阶段
     */
    private int getStageByHeight(double height) {
        if (height > 100) return 6; // 成熟期
        else if (height > 80) return 5; // 结果期
        else if (height > 50) return 4; // 开花期
        else if (height > 20) return 3; // 生长期
        else if (height > 5) return 2; // 幼苗
        else if (height > 0) return 1; // 发芽
        else return 0; // 种子
    }

    /**
     * 打印当前状态
     */
    private void printStatus(double height, String stage) {
        System.out.println("--- " + cropType + " 生长状态 ---");
        System.out.println("生长阶段: " + stage);
        System.out.println("当前高度: " + height + " cm");
        System.out.println("---------------------");
    }

    /**
     * 获取当前状态
     */
    public Map<String, Object> getStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("cropType", cropType);
        status.put("stage", GROWTH_STAGES[(int) stageSensor.getCurrentValue()]);
        status.put("height", heightSensor.getCurrentValue());
        return status;
    }

}
